package cloud.zhixinglu.www.spring.boot.paho.mqtt.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.context.annotation.Configuration;

/**
 * Mqtt发送端回调
 * @author  xct
 * @date  2021/7/30 16:00
 */
@Slf4j
@Configuration
public class MqttProviderCallBack implements MqttCallback {

	/**
	 * 与服务器断开连接的回调
	 * @author xct
	 * @param throwable Throwable
	 * @return void
	 * @date 2021/7/30 16:19
	 */
	@Override
	public void connectionLost(Throwable throwable) {
		log.debug("mqtt provider connection lost, try to reconnect");
	}

	/**
	 * 消息到达的回调
	 * @author xct
	 * @param s String
	 * @param mqttMessage MqttMessage
	 */
	@Override
	public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
		log.debug("生产者消息到达的回调：" + s + " , 消息：" + new String(mqttMessage.getPayload()));
	}

	/**
	 * 消息发布成功的回调
	 * @param iMqttDeliveryToken IMqttDeliveryToken
	 */
	@Override
	public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
		try{
			log.debug("MQTT消息发布成功：" +
					"消息ID：" + iMqttDeliveryToken.getMessageId() +
					"消息内容：" + iMqttDeliveryToken.getMessage());
		} catch (MqttException me){
			me.printStackTrace();
			log.error("MQTT错误信息：" + me.getMessage());
		}

	}

}
